package com.demo.interview.a1b2c3;

import java.util.concurrent.CountDownLatch;

/**
 * @author shenguangyang
 */
public class T01_sync_wait_notify {
    public static void main(String[] args) {
        // 实现某个线程先打印
        CountDownLatch latch = new CountDownLatch(1);
        final Object o = new Object();

        char[] aI = "ABCDEF".toCharArray();
        char[] aC = "123456".toCharArray();

        Thread t1;
        Thread t2;

        t1 = new Thread(() -> {
            try {
                latch.await();
            }catch (Exception e) {
                System.out.println(e.getMessage());
            }
            synchronized (o) {
                try {
                    for (char c : aI) {
                        System.out.print(c);
                        o.notify();
                        o.wait();
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    o.notify(); // 保证程序退出
                }
            }
        });

        t2 = new Thread(() -> {
            synchronized (o) {
                try {
                    for (char c : aC) {
                        System.out.print(c);
                        latch.countDown();
                        o.notify();
                        o.wait();
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    o.notify(); // 保证程序退出
                }
            }
        });

        t1.start();
        t2.start();
    }
}
